package com.hjwoo.app.fragment;

import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hjwoo.app.R;
import com.hjwoo.app.been.FailureResultObject;
import com.hjwoo.app.been.QueryContact;
import com.hjwoo.app.been.RegisterResult;
import com.hjwoo.app.been.UserAccessTokenOBJ;
import com.hjwoo.app.common.LoanApplication;
import com.hjwoo.app.net.RequestListener;
import com.hjwoo.app.net.RequestMethod;
import com.hjwoo.app.net.RequestTag;
import com.hjwoo.app.ui.CenterAlertDialog;
import com.hjwoo.app.ui.ModifyAvatarDialog;
import com.hjwoo.app.ui.RoundImageView;
import com.hjwoo.app.ui.VCodeButton;
import com.hjwoo.app.utils.JsonParser;
import com.hjwoo.app.utils.LoanAccessTokenIdKeeper;
import com.hjwoo.app.utils.LoanLog;
import com.hjwoo.app.utils.LoanToast;
import com.hjwoo.app.utils.Utils;
import com.hjwoo.app.views.OrdersActivity;
import com.hjwoo.app.views.RegisterActivity;
import com.hjwoo.app.views.RetrievePasswordActivity;
import com.hjwoo.app.views.UserCenterActivity;

import org.xutils.common.Callback;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;

public class UserCenterFragment extends Fragment implements View.OnClickListener, RequestListener {

    public static final String TAG = "UserCenterFragment";

    public static final int REGISTER_RESULT_CODE = 1;// 登陆结果
    public static final int USERINFO_RESULT_CODE = 2;// 编辑用户资料

    public static final int USER_ISLOGIN = 1;// 判断在其他界面返回时是否登录成功

    public static final String ITEMNAME = "itemName";// 所要传递的标题名称
    public static final File FILE_SDCARD = Environment
            .getExternalStorageDirectory();
    public static final File FILE_LOCAL = new File(FILE_SDCARD, "hjwoo");
    public static final File FILE_PIC_SCREENSHOT = new File(FILE_LOCAL, "headImage");
    private static String localTempImageFileName = "headimgtemp.png";
    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_CHOOSE_PHONE = 6;
    //是不是账号登录
    boolean isAccountLogin = true;
    //是不是登录状态
    boolean isLogin = false;
    UserAccessTokenOBJ userAccessTokenOBJ;
    private QueryContact queryContact;
    private LinearLayout usercenter_nologin_include;
    private LinearLayout usercenter_islogin_include;
    private TextView usercenter_account_ll_tv01, usercenter_account_ll_tv02, usercenter_verification_ll_tv01, usercenter_verification_ll_tv02, regist_tv;
    private LinearLayout user_exit_ll;
    private EditText et_username, et_userpwd, vcode, vphone;
    private Gson gson = new Gson();
    //     GridView descover_gv;
    private int[] imageViewIds;
    private String[] menuStrs;
    private VCodeButton vCodeButton;
    //个人信息的显示
    private TextView usercenter_username_tv, usercenter_cellphone_tv, usercenter_city_tv;
    //编辑图标
    private ImageView usercenter_edit_iv;
    //            et_username = (EditText)view.findViewById(R.id.et_username);
//    et_userpwd = (EditText)view.findViewById(R.id.et_userpwd);
    private View thisView;
    private MyUserCenterHandler myUserCenterHandler = null;
    //    private ImageView userhead;
    private RoundImageView userhead;
    private CheckBox vispassword;
    private Bitmap uploadbimap;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            // 不在最前端界面显示
        } else {// 重新显示到最前端中
            userAccessTokenOBJ = LoanAccessTokenIdKeeper.readAccessToken(LoanApplication.getInstance());
            if (!userAccessTokenOBJ.getAppSessionId().equals("")) {
                isLogin = true;
                changeAccountView();
            } else {
                isLogin = false;
                changeAccountView();
            }
        }
    }

    /**
     * 判断是否是登录状态
     */
    public void refreshLoginstatus() {
        userAccessTokenOBJ = LoanAccessTokenIdKeeper.readAccessToken(LoanApplication.getInstance());

        if (!userAccessTokenOBJ.getAppSessionId().equals("")) {
//            "登录状态"
            isLogin = true;
        } else {
//            "退出状态"
            isLogin = false;
        }
        changeAccountView();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_usercenter, container, false);
        thisView = view;
        initView(view);
        myUserCenterHandler = new MyUserCenterHandler();
        //设置handler
        LoanApplication.getInstance().setHandler(myUserCenterHandler);

        userAccessTokenOBJ = LoanAccessTokenIdKeeper.readAccessToken(LoanApplication.getInstance());
        if (!userAccessTokenOBJ.getAppSessionId().equals("")) {
            // "登录状态"设置个人信息
            RequestMethod.getMethod().appQueryContactBySessionId(userAccessTokenOBJ.getAppSessionId(), UserCenterFragment.this, getActivity());
        }
        return view;
    }

    /**
     * 切换是不是账号登录界面显示状态
     */
    private void changeAccountView() {
        if (isLogin) {
            //登录状态
            if (usercenter_nologin_include != null) {
                usercenter_nologin_include.setVisibility(View.INVISIBLE);
            }
            if (usercenter_nologin_include != null) {
                usercenter_islogin_include.setVisibility(View.VISIBLE);
            }
        } else {
            usercenter_nologin_include.setVisibility(View.VISIBLE);
            usercenter_islogin_include.setVisibility(View.INVISIBLE);
            //判断是不是账号登录
            if (isAccountLogin) {
                thisView.findViewById(R.id.account_login_ll).setVisibility(View.VISIBLE);
                thisView.findViewById(R.id.verificationcode_login_ll).setVisibility(View.INVISIBLE);
                usercenter_account_ll_tv01.setTextColor(ContextCompat.getColor(UserCenterFragment.this.getContext(), R.color.home_boder_color));
                usercenter_account_ll_tv02.setBackgroundColor(ContextCompat.getColor(UserCenterFragment.this.getContext(), R.color.home_boder_color));
                usercenter_verification_ll_tv01.setTextColor(ContextCompat.getColor(UserCenterFragment.this.getContext(), R.color.gray_lager));
                usercenter_verification_ll_tv02.setBackgroundColor(ContextCompat.getColor(UserCenterFragment.this.getContext(), R.color.gray_lager));

            } else { //验证码登录
                thisView.findViewById(R.id.account_login_ll).setVisibility(View.INVISIBLE);
                thisView.findViewById(R.id.verificationcode_login_ll).setVisibility(View.VISIBLE);
                vCodeButton = (VCodeButton) thisView.findViewById(R.id.login_vcodebtn);
                vcode = (EditText) thisView.findViewById(R.id.vcodelogin_edit_vode);
                vphone = (EditText) thisView.findViewById(R.id.vcodelogin_edit_phone);
                vCodeButton.setOnClickListener(this);
                usercenter_account_ll_tv01.setTextColor(ContextCompat.getColor(UserCenterFragment.this.getContext(), R.color.gray_lager));
                usercenter_account_ll_tv02.setBackgroundColor(ContextCompat.getColor(UserCenterFragment.this.getContext(), R.color.gray_lager));
                usercenter_verification_ll_tv01.setTextColor(ContextCompat.getColor(UserCenterFragment.this.getContext(), R.color.home_boder_color));
                usercenter_verification_ll_tv02.setBackgroundColor(ContextCompat.getColor(UserCenterFragment.this.getContext(), R.color.home_boder_color));
            }
        }
    }

    void initView(View view) {
        vispassword = (CheckBox) view.findViewById(R.id.login_switchpwd);
        vispassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @TargetApi(Build.VERSION_CODES.CUPCAKE)
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    et_userpwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    //                            将光标定义到最后面
                    et_userpwd.setSelection(et_userpwd.getText().length());
                } else {
                    et_userpwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    //                            将光标定义到最后面
                    et_userpwd.setSelection(et_userpwd.getText().length());
                }
            }
        });
        userhead = (RoundImageView) view.findViewById(R.id.user_head_iv);
        userhead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.gc();
                ModifyAvatarDialog modifyAvatarDialog = new ModifyAvatarDialog(
                        getActivity(), R.style.Theme_Popdialog) {
                    // 选择本地相册
                    @Override
                    public void doGoToImg() {
                        this.dismiss();
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        startActivityForResult(intent, FLAG_CHOOSE_IMG);
                    }

                    // 选择相机拍照
                    @Override
                    public void doGoToPhone() {
                        this.dismiss();
                        String status = Environment.getExternalStorageState();
                        if (status.equals(Environment.MEDIA_MOUNTED)) {
                            try {
//                                localTempImageFileName = "";
                                localTempImageFileName = "headimgtemp.png";
//                                localTempImageFileName = String.valueOf((new Date()).getTime()) + ".png";
                                File filePath = FILE_PIC_SCREENSHOT;
                                if (!filePath.exists()) {
                                    filePath.mkdirs();
                                }
                                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                                File f = new File(filePath, localTempImageFileName);
                                // localTempImgDir和localTempImageFileName是自己定义的名字
                                Uri u = Uri.fromFile(f);
                                intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
                                startActivityForResult(intent, FLAG_CHOOSE_PHONE);
                            } catch (ActivityNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
                modifyAvatarDialog.show();
            }
        });
        usercenter_account_ll_tv01 = (TextView) view.findViewById(R.id.usercenter_account_ll_tv01);
        usercenter_account_ll_tv02 = (TextView) view.findViewById(R.id.usercenter_account_ll_tv02);
        usercenter_verification_ll_tv01 = (TextView) view.findViewById(R.id.usercenter_verification_ll_tv01);
        usercenter_verification_ll_tv02 = (TextView) view.findViewById(R.id.usercenter_verification_ll_tv02);

        //个人信息的显示
        usercenter_username_tv = (TextView) view.findViewById(R.id.usercenter_username_tv);
        usercenter_cellphone_tv = (TextView) view.findViewById(R.id.usercenter_cellphone_tv);
        usercenter_city_tv = (TextView) view.findViewById(R.id.usercenter_city_tv);
        //编辑图标
        usercenter_edit_iv = (ImageView) view.findViewById(R.id.usercenter_edit_iv);


        user_exit_ll = (LinearLayout) view.findViewById(R.id.user_exit_ll);

        et_username = (EditText) view.findViewById(R.id.et_username);
        et_userpwd = (EditText) view.findViewById(R.id.et_userpwd);

        regist_tv = (TextView) view.findViewById(R.id.regist_tv);

        view.findViewById(R.id.forgetpwd_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), RetrievePasswordActivity.class));
            }
        });
        view.findViewById(R.id.usercenter_quanbu_ll).setOnClickListener(this);
        view.findViewById(R.id.usercenter_yipingfang_ll).setOnClickListener(this);
        view.findViewById(R.id.usercenter_daishenhe_ll).setOnClickListener(this);
        view.findViewById(R.id.usercenter_yichushen_ll).setOnClickListener(this);
        view.findViewById(R.id.usercenter_yiyuyue_ll).setOnClickListener(this);
        view.findViewById(R.id.usercenter_yishenpi_ll).setOnClickListener(this);
        view.findViewById(R.id.usercenter_yifandian_ll).setOnClickListener(this);
        view.findViewById(R.id.usercenter_yishibai_ll).setOnClickListener(this);

        usercenter_edit_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//            编辑个人资料
                if (queryContact != null) {
                    Intent i = new Intent(UserCenterFragment.this.getActivity(), UserCenterActivity.class);
                    Bundle b = new Bundle();
                    b.putSerializable("queryContact", queryContact);
                    i.putExtras(b);
                    startActivityForResult(i, USERINFO_RESULT_CODE);
                } else {
                    LoanToast.showToastShort("网络有点卡，请稍后再试！", UserCenterFragment.this.getContext());
                }
            }
        });

        user_exit_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new CenterAlertDialog(
                        getActivity(), R.style.Theme_Popdialog, "提示", "您确认要退出？") {
                    @Override
                    public void doOK() {
                        //退出
                        LoanAccessTokenIdKeeper.clear(UserCenterFragment.this.getActivity());
                        refreshLoginstatus();
                        this.dismiss();
                    }
                }.show();

            }
        });

        view.findViewById(R.id.bt_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (thisView.findViewById(R.id.verificationcode_login_ll).getVisibility() == View.VISIBLE) {
                    //验证码登录
                    RequestMethod.getMethod().appLoginWithCode(vphone.getText().toString().trim(), vcode.getText().toString().trim(), UserCenterFragment.this, getActivity());
                    return;
                }
                //登录操作
                doLoginForPost();
            }
        });

        usercenter_nologin_include = (LinearLayout) view.findViewById(R.id.usercenter_nologin_include);
        usercenter_islogin_include = (LinearLayout) view.findViewById(R.id.usercenter_islogin_include);

        regist_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intentForLoginOrRegist = new Intent(UserCenterFragment.this.getContext(),
                        RegisterActivity.class);
                // 返回码为4
                startActivityForResult(intentForLoginOrRegist, REGISTER_RESULT_CODE);
            }
        });

        //刷新
//        refreshLoginstatus();
        view.findViewById(R.id.usercenter_account_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isAccountLogin = true;
                changeAccountView();
            }
        });

        view.findViewById(R.id.usercenter_verification_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isAccountLogin = false;
                changeAccountView();
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        LoanLog.e("user", "onresume");
        refreshLoginstatus();
    }

    /**
     * 登录
     */
    private void doLoginForPost() {
        // 存储值时的登录尝试。
        String email = et_username.getText().toString();
        String password = et_userpwd.getText().toString();
        // 显示一个进度转轮,启动一个后台任务
        //执行用户的登录尝试
        RequestMethod.getMethod().doLoginMsg(email, password, UserCenterFragment.this, getActivity());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case REGISTER_RESULT_CODE:// 登录结果
                if (data != null) {
                    data.getBooleanExtra("loginFlag", false);
                    refreshLoginstatus();
//                    forHeadView();
//                    AsyncTaskOperationForCategory();
                }
                break;
            case USERINFO_RESULT_CODE:// 编辑用户资料

                if (data != null) {
                    //更新个人信息
//                    RequestMethod.getMethod().appQueryContactBySessionId(LoanAccessTokenIdKeeper.readAccessToken(LoanApplication.getInstance()).getAppSessionId(), UserCenterFragment.this, getActivity());
                    updateUserIfo(data.getStringExtra("msg"));

                }
                break;
            case FLAG_CHOOSE_IMG://选择图库
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri == null) {
                        return;
                    }
                    if (!TextUtils.isEmpty(uri.getAuthority())) {
                        Cursor cursor = getActivity().getContentResolver().query(uri,
                                new String[]{MediaStore.Images.Media.DATA},
                                null, null, null);
                        if (null == cursor) {
                            Toast.makeText(getActivity(), "图片没找到", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        cursor.moveToFirst();
                        String path = cursor.getString(cursor
                                .getColumnIndex(MediaStore.Images.Media.DATA));
                        cursor.close();
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 75, stream);
                        uploadbimap = Utils.small(bitmap);
                        RequestMethod.getMethod().appUploadAvatar(LoanAccessTokenIdKeeper.readAccessToken(LoanApplication.getInstance()).getAppSessionId(), Utils.bitmapToString(uploadbimap), UserCenterFragment.this, getActivity());
                        LoanLog.e("path=", path);
                    } else {
                        LoanLog.e("path=", uri.getPath());
                        Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath());
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 75, stream);
                        uploadbimap = Utils.small(bitmap);
                        RequestMethod.getMethod().appUploadAvatar(LoanAccessTokenIdKeeper.readAccessToken(LoanApplication.getInstance()).getAppSessionId(), Utils.bitmapToString(uploadbimap), UserCenterFragment.this, getActivity());

                    }
                }
                break;
            case FLAG_CHOOSE_PHONE://使用相机拍照
                LoanLog.e("FILE_PIC_SCREENSHOT:",FILE_PIC_SCREENSHOT.getPath());
                LoanLog.e("FILE_PIC_SCREENSHOT2:",localTempImageFileName);
                File f = new File(FILE_PIC_SCREENSHOT.getPath(), localTempImageFileName);

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 3;

                Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),options);
                if (bitmap == null) {
                    LoanToast.showToastLong("请重新选取",UserCenterFragment.this.getContext());
                    return;
                }
                uploadbimap = Utils.small(bitmap);
                userhead.setImageBitmap(uploadbimap);
                RequestMethod.getMethod().appUploadAvatar(LoanAccessTokenIdKeeper.readAccessToken(LoanApplication.getInstance()).getAppSessionId(), Utils.bitmapToString(uploadbimap), UserCenterFragment.this, getActivity());
                bitmap.recycle();
                break;
        }
//        }
    }

//    private Bitmap small(Bitmap bitmap) {
//        Matrix matrix = new Matrix();
//        matrix.postScale(0.2f, 0.2f); //长和宽放大缩小的比例
//        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
//        return resizeBmp;
//    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.usercenter_quanbu_ll:
//                全部订单
                startActivity(new Intent(UserCenterFragment.this.getActivity(), OrdersActivity.class).putExtra("stages", new String[]{"信息已完善","评房申请已提交", "评房已完成", "报单申请已提交", "基础材料已提供", "房产初审已完成", "预约申请已提交", "预约已指派", "产调已完成", "征信查询已完成", "下户已完成", "审批已完成", "抵押公证手续已完成", "放款已完成", "返点已完成"})
                        .putExtra(ITEMNAME, "全部订单").putExtra("status", new String[]{"成功", "失败"}));
                break;
            case R.id.usercenter_yipingfang_ll:
//                已评房
                startActivity(new Intent(UserCenterFragment.this.getActivity(), OrdersActivity.class).putExtra("stages", new String[]{"评房已完成"})
                        .putExtra(ITEMNAME, "已评房").putExtra("status", new String[]{"成功"}));
                break;
            case R.id.usercenter_yichushen_ll:
//                已初审
                startActivity(new Intent(UserCenterFragment.this.getActivity(), OrdersActivity.class).putExtra("stages", new String[]{"房产初审已完成"})
                        .putExtra(ITEMNAME, "已初审").putExtra("status", new String[]{"成功"}));
                break;
            case R.id.usercenter_yiyuyue_ll:
//              已预约
                startActivity(new Intent(UserCenterFragment.this.getActivity(), OrdersActivity.class).putExtra("stages", new String[]{"预约申请已提交", "预约已指派", "产调已完成", "征信查询已完成", "下户已完成"})
                        .putExtra(ITEMNAME, "已预约").putExtra("status", new String[]{"成功"}));
                break;
            case R.id.usercenter_daishenhe_ll:
//                待审核
                startActivity(new Intent(UserCenterFragment.this.getActivity(), OrdersActivity.class).putExtra("stages", new String[]{"报单申请已提交", "基础材料已提供"})
                        .putExtra(ITEMNAME, "待审核").putExtra("status", new String[]{"成功"}));
                break;
            case R.id.usercenter_yishenpi_ll:
//                已审批
                startActivity(new Intent(UserCenterFragment.this.getActivity(), OrdersActivity.class).putExtra("stages", new String[]{"审批已完成", "抵押公证手续已完成", "放款已完成"})
                        .putExtra(ITEMNAME, "已审批").putExtra("status", new String[]{"成功"}));
                break;
            case R.id.usercenter_yifandian_ll:
//                已返点
                startActivity(new Intent(UserCenterFragment.this.getActivity(), OrdersActivity.class).putExtra("stages", new String[]{"返点已完成"})
                        .putExtra(ITEMNAME, "已返点").putExtra("status", new String[]{"成功"}));
                break;
            case R.id.usercenter_yishibai_ll:
//                已失败
                startActivity(new Intent(UserCenterFragment.this.getActivity(), OrdersActivity.class).putExtra("stages", new String[]{"评房申请已提交", "评房已完成", "报单申请已提交", "基础材料已提供", "房产初审已完成", "预约申请已提交", "预约已指派", "产调已完成", "征信查询已完成", "下户已完成", "审批已完成", "抵押公证手续已完成", "放款已完成", "返点已完成"})
                        .putExtra(ITEMNAME, "已失败").putExtra("status", new String[]{"失败"}));
                break;
            case R.id.login_vcodebtn:
                if (TextUtils.isEmpty(vphone.getText().toString().trim())) {
                    LoanToast.showToastShort("请输入您的手机号码！", UserCenterFragment.this.getActivity());
                    return;
                }
                vCodeButton.startCount();
                RequestMethod.getMethod().appSendVerifiedCode(vphone.getText().toString().trim(), "Login", UserCenterFragment.this, getActivity());
                break;
        }
    }

    /**
     * 更新用户信息
     *
     * @param message
     */
    private void updateUserIfo(String message) {
        queryContact = new QueryContact();
        queryContact = gson.fromJson(message, QueryContact.class);
        usercenter_username_tv.setText("欢迎您，" + queryContact.getFullName());
        usercenter_cellphone_tv.setText(queryContact.getCellphone());
        usercenter_city_tv.setText(queryContact.getCity());
    }

    @Override
    public void requestSuccess(String tag, String message) {

        switch (tag) {
            case RequestTag.APPLOGIN:
                saveLogin(message);
                break;
            case RequestTag.APPLOGINWITHCODE:
                saveLogin(message);
                break;
            case RequestTag.APPQUERYCONTACTBYSESSIONID:
                //设置用户信息
                updateUserIfo(message);

                ImageOptions imageOptions = new ImageOptions.Builder()
//                        .setSize(DensityUtil.dip2px(120), DensityUtil.dip2px(120))//图片大小
//                        .setRadius(DensityUtil.dip2px(5))//ImageView圆角半径
                        .setCrop(true)// 如果ImageView的大小不是定义为wrap_content, 不要crop.
                        .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
//                        .setLoadingDrawableId(null)//加载中默认显示图片
//                        .setFailureDrawableId(R.mipmap.ic_launcher)//加载失败后默认显示图片
                        .build();

//                        x.image().bind(userhead,
//                                queryContact.getAvatar(),
//                        imageOptions);

//                x.image().bind(userhead,  queryContact.getAvatar(),imageOptions);

                LoanLog.e("img", "img:" + queryContact.getAvatar());

                if (queryContact.getAvatar() != null) {
                    //如果地址
                    x.image().loadDrawable(queryContact.getAvatar(), imageOptions, new Callback.CacheCallback<Drawable>() {
                        @Override
                        public boolean onCache(Drawable result) {
                            LoanLog.e("onCache", "获取头像图片~~~~~");
                            BitmapDrawable bd = (BitmapDrawable) result;
                            userhead.setImageBitmap(bd.getBitmap());
                            return true;
                        }

                        @Override
                        public void onSuccess(Drawable result) {
                            LoanLog.e("onSuccess", "获取图片~~~~~");
                            BitmapDrawable bd = (BitmapDrawable) result;
                            userhead.setImageBitmap(bd.getBitmap());
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            LoanLog.e("onError", "获取头像图片~~~~~" + ex.getLocalizedMessage() + ";" + ex.getMessage() + " ； " + ex.getCause());
                            LoanToast.showToastShort("获取头像失败", UserCenterFragment.this.getActivity());
                        }

                        @Override
                        public void onCancelled(CancelledException cex) {
                            LoanLog.e("onCancelled", "获取头像~~~~~");
                        }

                        @Override
                        public void onFinished() {
                            Log.e("onFinished", "获取图片~~~~~");
                        }
                    });
                }


                break;
            case RequestTag.APPUPLOADAVATAR:
                RequestMethod.getMethod().appQueryContactBySessionId(LoanAccessTokenIdKeeper.readAccessToken(LoanApplication.getInstance()).getAppSessionId(), UserCenterFragment.this, getActivity());

                break;
        }
        //请求成功将网络异常的图片设置成隐藏
    }

    //保存登录状态
    public void saveLogin(String message) {
        if (TextUtils.isEmpty(message)) {
            LoanToast.showToastShort("登录异常", UserCenterFragment.this.getActivity());
            return;
        }
        RegisterResult rr = gson.fromJson(message, RegisterResult.class);

        LoanToast.showToastShort("登录成功", UserCenterFragment.this.getActivity());

        userAccessTokenOBJ = new UserAccessTokenOBJ();
        userAccessTokenOBJ.setAppSessionId(rr.getAppSessionId());

        //将id保存
        LoanAccessTokenIdKeeper.writeAccessToken(UserCenterFragment.this.getActivity(), userAccessTokenOBJ);
        refreshLoginstatus();
        //设置个人信息
        RequestMethod.getMethod().appQueryContactBySessionId(userAccessTokenOBJ.getAppSessionId(), UserCenterFragment.this, getActivity());
    }

    @Override
    public void requestError(String message) {
        FailureResultObject failureResultObject = new FailureResultObject();
        failureResultObject = JsonParser.getJsonParser().parserJsonToObj(message, FailureResultObject.class);
        if (failureResultObject.getErrorCode().equals("4400")) {
            refreshLoginstatus();
        }
        LoanToast.showToastShort(failureResultObject.getErrorMessage(), UserCenterFragment.this.getActivity());
    }

    /**
     * 自己实现 Handler 处理消息更新UI
     *
     * @author mark
     */
    public final class MyUserCenterHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == UserCenterFragment.USER_ISLOGIN) { // 表示已经更新UI
                //刷新obj
                userAccessTokenOBJ = LoanAccessTokenIdKeeper.readAccessToken(LoanApplication.getInstance());
                //设置个人信息
                RequestMethod.getMethod().appQueryContactBySessionId(userAccessTokenOBJ.getAppSessionId(), UserCenterFragment.this, UserCenterFragment.this.getActivity());
            }
        }
    }
}